<template>
	<el-card>
		<div class="top-main">
			<div class="top-search">
				<el-form :inline="true" :model="state.queryForm" class="demo-form-inline">
					<el-form-item label="标准名称">
						<el-input v-model="state.queryForm.standardName" placeholder="请输入标准名称" />
					</el-form-item>
					<el-form-item label="工程名称">
						<el-input v-model="state.queryForm.projectName" placeholder="请输入工程名称" />
					</el-form-item>
					<el-form-item label="执行情况">
						<el-select v-model="state.queryForm.implementationStatus" placeholder="请选择执行情况" clearable>
							<el-option label="符合" value="1" />
							<el-option label="不符合" value="0" />
						</el-select>
					</el-form-item>
					<el-form-item label="使用该标准">
						<el-select v-model="state.queryForm.isStandard" placeholder="是否使用该标准" clearable>
							<el-option label="是" value="1" />
							<el-option label="否" value="0" />
						</el-select>
					</el-form-item>
					<el-form-item label="日期范围">
						<el-date-picker
							v-model="state.queryForm.date"
							type="daterange"
							range-separator="-"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							value-format="YYYY-MM-DD 00:00:00"
							format="YYYY MM-DD"
							@change="handleDateChange"
						/>
					</el-form-item>

					<el-form-item>
						<div class="top-btn">
							<el-button type="primary" icon="Search" @click="handleSearch">查询</el-button>
							<el-button icon="RefreshRight" @click="handleReset">重置</el-button>
						</div>
					</el-form-item>
				</el-form>
			</div>
		</div>
	</el-card>
	<el-card>
		<div class="second-content">
			<!-- <el-button size="large">
				<el-icon>
					<RefreshLeft />
				</el-icon>
			</el-button> -->

			<el-button type="primary" @click="addOrUpdateHandle(false, {}, false)">新增</el-button>

			<!-- <el-button type="primary" @click="submitHandle">发布</el-button>
			<el-button type="primary" @click="releaseHandle">取消发布</el-button> -->
			<el-button type="success" @click="exportHandle">导出汇总数据</el-button>
		</div>
		<el-table ref="multipleTableRef" v-loading="state.dataListLoading" :data="state.dataList" stripe class="layout-table">
			>

			<el-table-column type="selection" header-align="center" align="center" width="55" fixed="left" />
			<el-table-column prop="standardName" label="标准名称" header-align="center" align="center" />
			<el-table-column prop="projectName" label="工程名称" header-align="center" align="center" />
			<el-table-column prop="designInstitute" label="设计单位" header-align="center" align="center" />
			<el-table-column prop="drawingReviewUnit" label="审图单位" header-align="center" align="center" />
			<el-table-column prop="constructionUnit" label="施工单位" header-align="center" align="center" />
			<el-table-column prop="name" label="执行情况" header-align="center" align="center">
				<template #default="scope">
					<el-tag v-if="scope.row.implementationStatus == 1" type="success">符合</el-tag>
					<el-tag v-else type="danger">不符合</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="name" label="是否使用该标准" header-align="center" align="center">
				<template #default="scope">
					<el-tag v-if="scope.row.isStandard == 1" type="success">是</el-tag>
					<el-tag v-else type="danger">否</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="120">
				<template #default="scope">
					<el-icon :size="16" color="#1491FF" title="编辑" style="cursor: pointer; margin: 0 6px" @click="addOrUpdateHandle(false, scope.row, true)">
						<Edit />
					</el-icon>
					<el-icon :size="16" color="#1491FF" title="查看" style="cursor: pointer; margin: 0 6px" @click="addOrUpdateHandle(true, scope.row, true)">
						<View />
					</el-icon>
					<el-icon :size="16" color="#fe6360" title="删除" style="cursor: pointer; margin: 0 6px" @click="deleteBatchHandle(scope.row.id)">
						<Delete />
					</el-icon>
				</template>
			</el-table-column>
		</el-table>

		<el-pagination
			:current-page="state.queryForm.pageNum"
			:page-size="state.queryForm.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		>
		</el-pagination>

		<updateMandatory ref="updateRef" @refresh-data-list="getDataList"></updateMandatory>
	</el-card>
</template>

<script setup lang="ts">
import { qiangzhideleteApi, qiangzhilistApi, qiangzhiunpublishApi, qiangzhiununPublishApi } from '@/api/government'
import { useUserStore } from '@/store/modules/user'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import updateMandatory from './components/updateMandatory.vue'
const userStore = useUserStore()
const state = reactive({
	queryForm: {
		standardName: '',
		projectName: '',
		isStandard: '',
		implementationStatus: '',
		startDate: '',
		endDate: '',
		date: [],
		pageNum: 1,
		pageSize: 10
	},
	total: 1,
	dataListLoading: false,
	dataList: [],
	ids: []
})
const multipleTableRef = ref<TableInstance>()
const updateRef = ref()
const handleDateChange = val => {
	// 清空时，val 为 null，手动设置为空字符串

	state.queryForm.date = val || [] // 清空时重置为空数组
	state.queryForm.endDate = val ? val[1] : ''
	state.queryForm.startDate = val ? val[0] : ''
}

const xuanguanUpdateRef = ref()
const addOrUpdateHandle = (isUpdate: Boolean, row: any, isChakan: Boolean) => {
	updateRef.value.init(isUpdate, row, isChakan)
}
const deleteBatchHandle = (id: String | Number) => {
	ElMessageBox.confirm('是否删除?', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			delMethods(id)
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败'
			})
		})
}

const delMethods = async (id: String | Number) => {
	await qiangzhideleteApi(id).then(res => {
		ElMessage.success('删除成功')
		handleReset()
	})
}

const exportHandle = () => {
	try {
		// const selectedRows = multipleTableRef.value.getSelectionRows()
		// if (selectedRows.length == 0) {
		// 	throw new Error('请选择一个项目')
		// }
		// const ids = selectedRows.map(item => {
		// 	return item.id
		// })
		const param = {
			// ids: ids,
			...state.queryForm
		}
		axios({
			method: 'get',
			url: window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/mandatoryProvision/export',
			headers: {
				'Content-Type': 'application/json;charset=UTF-8',
				Authorization: userStore.token
			},
			data: param,
			responseType: 'blob'
		})
			.then(response => {
				ElMessage.success('操作成功，文件已开始下载')
				const blob = new Blob([response.data], {
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				})
				const url = window.URL.createObjectURL(blob)
				const a = document.createElement('a')
				a.href = url
				a.download = '强制性条文汇总.xlsx'
				a.click()
				window.URL.revokeObjectURL(url)
			})
			.catch(error => {
				console.error('导出失败:', error)
			})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

onMounted(() => {
	getDataList()
})
const handleSearch = () => {
	state.queryForm.pageNum = 1
	getDataList()
}

const handleReset = () => {
	state.queryForm.standardName = ''
	state.queryForm.projectName = ''
	state.queryForm.isStandard = ''
	state.queryForm.implementationStatus = ''
	state.queryForm.startDate = ''
	state.queryForm.endDate = ''
	state.queryForm.date = []
	state.queryForm.startDate = ''
	state.queryForm.pageNum = 1

	getDataList()
}

const getDataList = () => {
	state.dataListLoading = true
	delete state.queryForm.date
	qiangzhilistApi({
		...state.queryForm
	}).then(res => {
		state.dataListLoading = false
		state.dataList = res.data.list || []
		state.total = res.data.total || 0
	})
}

const onSubmit = () => {
	console.log('submit!')
}
const tableData = []
const handleCurrentChange = (val: number) => {
	state.queryForm.pageNum = val
	state.dataList = []
	getDataList()
}
const handleSizeChange = (val: number) => {
	state.queryForm.pageSize = val
	state.dataList = []
	getDataList()
}

const onUpdate = () => {
	updateRef.value.init()
}

const submitHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请至少选择一个项目')
		}

		const ids = selectedRows.map(item => {
			return item.id
		})

		ElMessageBox.confirm('是否发布?', '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => {
				qiangzhiunpublishApi({ ids: ids }).then(res => {
					ElMessage.success('发布成功')
					handleReset()
				})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '删除失败'
				})
			})
	} catch (error) {
		showToast(error.message, 'error')
	}
}

const releaseHandle = () => {
	try {
		const selectedRows = multipleTableRef.value.getSelectionRows()
		if (selectedRows.length == 0) {
			throw new Error('请至少选择一个项目')
		}

		const ids = selectedRows.map(item => {
			return item.id
		})

		ElMessageBox.confirm('是否确认取消发布?', '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		})
			.then(() => {
				qiangzhiununPublishApi({ ids: ids }).then(res => {
					ElMessage.success('取消发布成功')
					handleReset()
				})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '删除失败'
				})
			})
	} catch (error) {
		showToast(error.message, 'error')
	}
}
</script>
<style scoped>
.top-main {
	display: flex;
}

.top-search {
	display: flex;
}

.top-btn {
	display: flex;
}

.second-content {
	display: flex;
	justify-content: flex-end;
	margin-bottom: 20px;
}
</style>
